package com.eugenema.util.ExcelUtil;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 列长度控制
 *
 * @author 马寅广
 * @date 2023/3/16 16:52
 *
 **/
public class CustomColumnWidth extends AbstractColumnWidthStyleStrategy {
    private Map<Integer, Map<Integer, Integer>> cache = new HashMap<>();

    /** 列序号 */
    private Integer columnIndex;
    /** 列宽 */
    private Integer columnWidth;

    public CustomColumnWidth(Integer columnIndex, Integer columnWidth) {
        this.columnIndex = columnIndex;
        this.columnWidth = columnWidth;
    }

    @Override
    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        /** 当前列 */
        int currentIndex = cell.getColumnIndex();

        //判断是否是指定列
        if (currentIndex != columnIndex) {
            return;
        }

        //获取缓存宽度
        Map<Integer, Integer> maxColumnWidthMap = cache.computeIfAbsent(writeSheetHolder.getSheetNo(), key -> new HashMap<>(16));
        //设置列宽
        maxColumnWidthMap.put(currentIndex, columnWidth);
        writeSheetHolder.getSheet().setColumnWidth(currentIndex, columnWidth * 256);
    }
}
